import Vue from 'vue';

var contactId = 0;

export default {
	state:{
		items: [],
		own: {}
	},
	mutations: {
		USER_INIT(state,info) {
			state.items = info.items;
			state.own = info.own;
		},
		USER_ADD(state,user) {
			user.id = contactId ++;
			user.imgSrc = '/static/img/userImg.png';
			state.items.push(user);
			console.log(JSON.parse(localStorage.items) instanceof Array);
			console.log(JSON.parse(localStorage.items).push(user));
	// 以上输出结果为true和16，浏览器里提取的JSON转换成数组后直接push值进去，
	//就变成数组长度了。要把转换后的数组赋值给一个变量，才能push值。
			let arr = JSON.parse(localStorage.items);
			arr.push(user);
			localStorage.items = JSON.stringify(arr);
		},
		USER_REMOVE(state,userId) {
			state.items = state.item.filter((item) => {
				return item.id !== userId;
			})
		},
		USER_CHANGE(state,user) {
			for(var key in state.items) {
				if(state.items[key].id === user.id) {
					state.items[key].name = user.name;
					state.items[key].tel = user.tel;
				}
			}
		},
		OWN_CHANGE(state,user) {
			state.own = user;
			sessionStorage.setItem('user',JSON.stringify(user));
			localStorage.setItem(sessionStorage.userId,JSON.stringify(user));
		}
	},
	actions: {
		userInit({commit}) {
			if(sessionStorage.login && sessionStorage.login == 1) {
				let items = [
				    {name: '妈妈', tel: 1234555656, status: "亲人"},
                    {name: 'nic', tel: 1234555656, status: "朋友"},
                    {name: '爸爸', tel: 1234555656, status: "亲人"},
                    {name: 'wind', tel: 1234555656, status: "朋友"},
                    {name: 'lily', tel: 1234555656, status: "同学"},
                    {name: '爷爷', tel: 1234555656, status: "亲人"},
                    {name: 'tom', tel: 1234555656, status: "同学"},
                    {name: 'tom', tel: 1234555656, status: "同学"},
                    {name: 'tom', tel: 1234555656, status: "同学"},
                    {name: 'tom', tel: 1234555656, status: "同学"},
                    {name: '外婆', tel: 1234555656, status: "亲人"},
                    {name: 'tom', tel: 1234555656, status: "同学"},
                    {name: 'tom', tel: 1234555656, status: "同学"},
                    {name: 'tom', tel: 1234555656, status: "同学"},
                    {name: '外婆', tel: 1234555656, status: "亲人"},
				];
				items = items.filter((item) => {
					item.id = contactId ++;
					item.imgSrc = '/static/img/userImg.png';
					return item;
				});
				if(!localStorage.items) {
					localStorage.items = JSON.stringify(items);				
				} else {
					items = JSON.parse(localStorage.getItem('items'));
				};
				let own = JSON.parse(sessionStorage.user);

				commit('USER_INIT',{
					items: items,
					own: own
				});
			} else {
				alert('请先登入！');
				router.replace('/home/login');
			}
		},
		userAdd({commit}, user) {
			commit('USER_ADD', user);
		},
		userRemove({commit}, userId) {
			commit('USER_REMOVE', userId);
		},
		userChange({commit}, user) {
			commit('USER_CHANGE', user);
		},
		ownChange({commit}, user) {
			commit('OWN_CHANGE', user);
		}
	}
}